package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import cn.tedu._05weibo.base.utils.CacheUtil;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVo;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * @Author Justin Parker
 * @Date 2024/8/9 0009 11:22
 * @Version 1.0
 */
@Api(tags = "02.微博模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/v1/weibo")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
//  @Autowired
//  private RedisTemplate<String,Serializable> redisTemplate;
    //装配缓存工具类
    @Autowired
    private CacheUtil cacheUtil;

    @ApiOperation(value = "发布微博功能")
    @PostMapping("/insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO,@ApiIgnore HttpSession session){
        //1.获取用户标识
        UserVo userVo =(UserVo) session.getAttribute("user");

        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO,weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVo.getId());
        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }

    @ApiOperation(value = "微博首页功能")
    @GetMapping("/selectIndex")
    public JsonResult selectByIdAll(){
        /*
            设计：Redis字符串缓存{"index_cache":weiboIndexVOS}
            1.从缓存[Redis]中获取首页数据：weiboIndexVOS;
                1.1 缓存中存在，直接返回；
                1.2 缓存中不存在:
                   * 从mysql数据库中查询数据：weiboIndexVOS;
                   * 将数据保存到缓存[Redis]中：weiboIndexVOS，
                   * 返回结果。
         */
//        Serializable indexCache = redisTemplate.opsForValue().get("index_cache");
        Serializable indexCache = cacheUtil.get("index_cache");
        //缓存中存在
        if (indexCache != null){
            System.out.println("数据来自缓存Redis");
            return JsonResult.ok(indexCache);
        }
        //缓存中不存在
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
//        redisTemplate.opsForValue().set("index_cache",(Serializable) weiboIndexVOS);
        cacheUtil.setExpire("index_cache",(Serializable) weiboIndexVOS,30);

        System.out.println("数据来自数据库MySQL");

        return JsonResult.ok(weiboIndexVOS);
    }

    @ApiOperation(value = "查询微博详情功能")
    @GetMapping("/selectById")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "微博编号",required = true,dataType = "long"),
            @ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "String")
    })
    public JsonResult selectById(@Range(min = 200,max = 300,message = "微博编号必须在200-300之间") @RequestParam Long id, String username){
        //手动抛异常，用来测试全局异常处理
        if (id < 0){
            throw new IllegalArgumentException("微博编号不能小于0");

        }
        //username只是为了Knife4j声明参数方式的参数描述测试，没有其他作用；
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);

        return  JsonResult.ok(weiboDetailVO);
    }
}
